#@reference Laptop Shop Tutorial   (Whitney Clare x11106131)

class User < ActiveRecord::Base
  has_many :products
  attr_accessor :password
  before_save :encrypt_password

  has_many :orders


  validates :email,
          :uniqueness => true,
          :length => {:within => 5..50}

  validates :password,
            :confirmation => true,
            :length => {:within => 4..20},
            :presence => true

  def self.authenticate(email, password)
      user = find_by_email (email)
      return user if user && user.authenticated?(password)
  end

  def authenticated?(password)
    self.hashed_password == encrypt(password)
  end

  protected
  def encrypt_password
    return if password.blank?
    self.hashed_password = encrypt (password)
  end

  def encrypt(string)
    Digest::SHA1.hexdigest(string)
  end


end
